﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using UnityEngine;

/// <summary>
/// 挂在任意一个对象上即起作用（作用：报错之后退出程序并打印错误日志）
/// </summary>
public class VIPExceptionHandler : MonoBehaviour {

    //是否作为异常处理者
    [SerializeField]
    private bool IsHandler = false;
    //是否退出程序当异常发生时
    [SerializeField]
    private bool IsQuitWhenException = true;
    //异常日志保存路径（文件夹）
    private string LogPath;
    //Bug反馈程序的启动路径
    private string BugExePath;

    private bool isExit = false;

    void Awake()
    {
        LogPath = Application.dataPath.Substring(0, Application.dataPath.LastIndexOf("/")) + "\\logs";
        BugExePath = Application.dataPath.Substring(0, Application.dataPath.LastIndexOf("/")) + "\\Bug.exe";

        //注册异常处理委托  
        if (IsHandler)
        {
            //Application.RegisterLogCallback(Handler);
            Application.logMessageReceived += Handler;
        }
    }

    void OnDestory()
    {
        //清除注册
        if (IsHandler)
        {
            //Application.RegisterLogCallback(null);
            Application.logMessageReceived -= Handler;
        }
    }

    //委托的形式
    //public delegate void LogCallback(string condition, string stackTrace, LogType type);
    //public enum LogType
    //{
    //    Error = 0, //Error为错误日志，Debug.LogError输出的日志便是此类型；
    //    Assert = 1, //Assert为Unity本身的异常，这种异常通常都是致命的，会导致整个进程crash；
    //    Warning = 2, //Warning为警告日志，Debug.LogWarning输出的日志便是此类型；
    //    Log = 3, //Log为普通日志，Debug.Log输出的日志便是此类型；
    //    Exception = 4, //Exception为被Unity捕获的未知异常，也就是我们自己的代码产生的异常，这将是我们处理的重点对象。
    //}
    void Handler(string logString, string stackTrace, LogType type)
    {
        if (type == LogType.Error || type == LogType.Exception || type == LogType.Assert)
        {
            string logPath = LogPath + "\\" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".log";
            //打印日志
            if (Directory.Exists(LogPath))
            {
                File.AppendAllText(logPath, "[time]:" + DateTime.Now.ToString() + "\r\n");
                File.AppendAllText(logPath, "[type]:" + type.ToString() + "\r\n");
                File.AppendAllText(logPath, "[exception message]:" + logString + "\r\n");
                File.AppendAllText(logPath, "[stack trace]:" + stackTrace + "\r\n");
            }
            else
            {
                //创建文件夹
                Directory.CreateDirectory(LogPath);
                File.AppendAllText(logPath, "[time]:" + DateTime.Now.ToString() + "\r\n");
                File.AppendAllText(logPath, "[type]:" + type.ToString() + "\r\n");
                File.AppendAllText(logPath, "[exception message]:" + logString + "\r\n");
                File.AppendAllText(logPath, "[stack trace]:" + stackTrace + "\r\n");
            }
            //启动bug反馈程序  
            if (File.Exists(BugExePath))
            {
                ProcessStartInfo pros = new ProcessStartInfo();
                pros.FileName = BugExePath;
                //pros.Arguments = logPath;
                Process pro = new Process();
                pro.StartInfo = pros;
                pro.Start();
            }
            //退出程序，bug反馈程序重启主程序  
            if (IsQuitWhenException && !isExit)
            {
                print("捕捉到了错误");
                isExit = true;
                Application.Quit();
            }
        }
    }

}
